package com.kky.pp.activity.member

import android.os.Bundle
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import com.kky.pp.common.Constant
import com.kky.pp.R
import com.kky.pp.adapter.MemberSubscriptionAdapter
import com.kky.pp.callback.EmptySuccessCallBack
import com.kky.pp.popup.CommonPopup
import com.kky.pp.entity.AgreementEntity
import com.kky.pp.entity.MemberSubscribeEntity
import io.rong.imkit.entity.OrderCreateEntity
import io.rong.imkit.event.FirebaseEventTag
import com.kky.pp.util.CollectionUtils
import com.kky.pp.view.Loading.LoadingDialog
import io.rong.imkit.utils.FirebaseEventUtils
import com.kky.pp.pay.GooglePayUtils
import com.custom.base.entity.OkHttpBodyEntity
import com.custom.base.http.OkHttpFromBoy
import com.custom.base.http.OkHttpManager
import com.custom.base.http.SDOkHttpResoutCallBack
import com.kky.pp.base.TitleBasePresenterImpl
import io.rong.imkit.activity.RongWebviewActivity


class MemberSubscriptionPresenter : TitleBasePresenterImpl<MemberSubscriptionContract.View>(),
    MemberSubscriptionContract.Presenter {


    var alreadyBuyProductCode: String = ""

    override fun onBackClick() {
        finish()
    }

    override fun initBundle(bundle: Bundle) {
        mView?.apply {
            getData()

            OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
                override fun addBody(requestBody: OkHttpBodyEntity) {
                    requestBody.setPost(Constant.user_config_url)
                    requestBody.add("code", 2)
                }
            }, object : SDOkHttpResoutCallBack<AgreementEntity>() {
                override fun onSuccess(entity: AgreementEntity) {
                    val style = SpannableStringBuilder()
                    style.append(mActivity.getString(R.string.agree_to_the_payment_agreement))

                    style.setSpan(object : ClickableSpan() {
                        override fun onClick(p0: View) {
                            val b = Bundle()
                            b.putString("url", entity.data.paymentAgreement)
                            b.putString(
                                "title",
                                mActivity.resources.getString(R.string.payment_agreement)
                            )
                            startActivity(RongWebviewActivity::class.java, b)
                        }

                        override fun updateDrawState(ds: TextPaint) {
                            ds.linkColor = ContextCompat.getColor(
                                mActivity,
                                R.color.color_999999
                            )
                            ds.isUnderlineText = true
                            ds.clearShadowLayer()
                        }
                    }, 13, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                    txtPaymentProtocol.text = style
                    txtPaymentProtocol.movementMethod = LinkMovementMethod.getInstance()
                }
            })


        }
        super<TitleBasePresenterImpl>.initBundle(bundle)
    }

    fun getData() {
        mView?.apply {

            LoadingDialog.showLoading(mActivity)
            OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
                override fun addBody(requestBody: OkHttpBodyEntity) {
                    requestBody.setPost(Constant.user_member_product_subscription_url)
                }

            }, object : SDOkHttpResoutCallBack<MemberSubscribeEntity>() {
                override fun onSuccess(entity: MemberSubscribeEntity) {
                    LoadingDialog.dismissLoading(mActivity)

                    FirebaseEventUtils.logEvent(if (entity.data.memberCode != null) FirebaseEventTag.Me_Member_Premium.name else FirebaseEventTag.Me_Nonmember_Premium.name)

                    txtVipBuyTitles.visibility = View.VISIBLE
                    txtVipBuyContents.visibility = View.VISIBLE

                    txtVipBuyTitles.text = entity.data.memberDescription.tip
                    txtVipBuyContents.text = entity.data.memberDescription.content

                    txtVipBuyDescTitle.isVisible =
                        !entity.data.memberDescription.header.isNullOrEmpty()
                    if (!entity.data.memberDescription.header.isNullOrEmpty()) {
                        txtVipBuyDescTitle.text =
                            entity.data.memberDescription.header
                    }

                    if (entity.data.memberCode != null)
                        txtVipBuyDates.text =
                            if (entity.data.autoRenew == 1) mActivity.getString(R.string.auto_subscription) else "Until: ${entity.data.expiryDate}"
                    txtVipBuyDates.visibility =
                        if (entity.data.memberCode != null) View.VISIBLE else View.GONE
                    txtVipBuyActions.visibility = if (entity.data.autoRenew == 2) View.GONE else {
                        if (entity.data.memberCode != null)
                            View.VISIBLE else View.GONE
                    }
                    conVipBuyContainers.visibility = View.VISIBLE
                    linearVipBuyBottomContainers.visibility =
                        if (entity.data.memberCode == null) View.VISIBLE else {
                            if (entity.data.autoRenew == 2) View.VISIBLE else View.GONE
                        }
                    var productCode = ""//产品码
                    if (CollectionUtils.isNotEmpty(entity.data.productDescriptions)) {
                        for (i in 0 until entity.data.productDescriptions.size) {
                            if (entity.data.productDescriptions[i].check) {
                                memberActionBuy.text =
                                    "${mActivity.getString(R.string.dollar_sign)}${entity.data.productDescriptions[i].price} ${
                                        mActivity.getString(R.string.purchase_now)
                                    }"
                                productCode = entity.data.productDescriptions[i].productCode
                                alreadyBuyProductCode =
                                    entity.data.productDescriptions[i].productCode

                                break
                            }
                        }


                        conVipBuyQuarterContainers.setBackgroundResource(if (entity.data.productDescriptions[2].check) R.drawable.shape_ccb0ff_c02ed8_stroke_2_radius_10 else R.drawable.shape_ccb0ff_radius_10)
                        txtVipBuyQuarterTitles.text = entity.data.productDescriptions[2].tip
                        txtVipBuyQuarterNumbers.text = entity.data.productDescriptions[2].benefitNum
                        txtVipBuyQuarterNames.text = entity.data.productDescriptions[2].benefitUnit
                        txtVipBuyQuarterDiscountedPrices.text = "$"+entity.data.productDescriptions[2].price

                        conVipBuyMonthlyContainers.setBackgroundResource(if (entity.data.productDescriptions[1].check) R.drawable.shape_ccb0ff_c02ed8_stroke_2_radius_10 else R.drawable.shape_ccb0ff_radius_10)
                        txtVipBuyMonthlyTitles.text = entity.data.productDescriptions[1].tip
                        txtVipBuyMonthlyNumbers.text = entity.data.productDescriptions[1].benefitNum
                        txtVipBuyMonthlyNames.text = entity.data.productDescriptions[1].benefitUnit
                        txtVipBuyMonthlyDiscountedPrices.text = "$"+entity.data.productDescriptions[1].price

                        conVipBuyWeeksContainers.setBackgroundResource(if (entity.data.productDescriptions[0].check) R.drawable.shape_ccb0ff_c02ed8_stroke_2_radius_10 else R.drawable.shape_ccb0ff_radius_10)
                        txtVipBuyWeeksNumbers.text = entity.data.productDescriptions[0].benefitNum
                        txtVipBuyWeeksNames.text = entity.data.productDescriptions[0].benefitUnit
                        txtVipBuyWeeksDiscountedPrices.text ="$"+ entity.data.productDescriptions[0].price


                        memberActionBuy.setOnClickListener {
                            if (entity.data.memberCode != null) {
                                val dialog =
                                    CommonPopup(mActivity).setTitle(mActivity.getString(R.string.purchase_new_subscription))
                                        .setContent(mActivity.getString(R.string.purchase_new_subscription_tips))
                                        .setConfirmText(mActivity.getString(R.string.purchase))
                                        .setCancelText(mActivity.getString(R.string.cancel))
                                dialog.setConfirmListener {
                                    OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
                                        override fun addBody(requestBody: OkHttpBodyEntity) {
                                            requestBody.setPost(Constant.user_create_order_url)
                                            requestBody.add("productCode", productCode)
                                            requestBody.add("productCategory", 1)
                                        }

                                    }, object : SDOkHttpResoutCallBack<OrderCreateEntity>() {
                                        override fun onSuccess(entity: OrderCreateEntity) {
                                            GooglePayUtils.instance.start(
                                                entity,
                                                mActivity,
                                                object : EmptySuccessCallBack {
                                                    override fun OnSuccessListener() {
                                                        FirebaseEventUtils.logEvent(FirebaseEventTag.Me_Member_Premiumsuccess.name)
                                                        getData()
                                                    }

                                                })
                                        }
                                    })
                                    dialog.dismiss()
                                }
                                dialog.showPopupWindow()
                            } else {
                                OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
                                    override fun addBody(requestBody: OkHttpBodyEntity) {
                                        requestBody.setPost(Constant.user_create_order_url)
                                        requestBody.add("productCode", productCode)
                                        requestBody.add("productCategory", 1)
                                    }

                                }, object : SDOkHttpResoutCallBack<OrderCreateEntity>() {
                                    override fun onSuccess(entity: OrderCreateEntity) {
                                        GooglePayUtils.instance.start(
                                            entity,
                                            mActivity,
                                            object : EmptySuccessCallBack {
                                                override fun OnSuccessListener() {
                                                    FirebaseEventUtils.logEvent(FirebaseEventTag.Me_Nonmember_Premiumsuccess.name)

                                                    getData()
                                                }

                                            })
                                    }
                                })
                            }
                        }

                        conVipBuyQuarterContainers.setOnClickListener {
                            conVipBuyQuarterContainers.setBackgroundResource(R.drawable.shape_ccb0ff_c02ed8_stroke_2_radius_10)
                            entity.data.productDescriptions[2].check = true

                            conVipBuyMonthlyContainers.setBackgroundResource(R.drawable.shape_ccb0ff_radius_10)
                            entity.data.productDescriptions[1].check = false

                            conVipBuyWeeksContainers.setBackgroundResource(R.drawable.shape_ccb0ff_radius_10)
                            entity.data.productDescriptions[0].check = false

                            memberActionBuy.text =
                                "${mActivity.getString(R.string.dollar_sign)}${entity.data.productDescriptions[2].price} ${
                                    mActivity.getString(R.string.purchase_now)
                                }"
                            productCode = entity.data.productDescriptions[2].productCode
                            txtVipBuyActions.visibility =
                                if (entity.data.autoRenew != 2) View.GONE else {
                                    if (entity.data.memberCode != null) View.GONE else {
                                        if (alreadyBuyProductCode != productCode) View.VISIBLE else View.GONE
                                    }
                                }
                            linearVipBuyBottomContainers.visibility =
                                if (entity.data.autoRenew == 2) View.VISIBLE else {
                                    if (entity.data.memberCode == null) View.VISIBLE else {
                                        if (alreadyBuyProductCode == productCode) View.GONE else View.VISIBLE
                                    }
                                }

                        }

                        conVipBuyMonthlyContainers.setOnClickListener {
                            conVipBuyQuarterContainers.setBackgroundResource(R.drawable.shape_ccb0ff_radius_10)
                            entity.data.productDescriptions[2].check = false



                            conVipBuyMonthlyContainers.setBackgroundResource(R.drawable.shape_ccb0ff_c02ed8_stroke_2_radius_10)
                            entity.data.productDescriptions[1].check = true

                            conVipBuyWeeksContainers.setBackgroundResource(R.drawable.shape_ccb0ff_radius_10)
                            entity.data.productDescriptions[0].check = false

                            productCode = entity.data.productDescriptions[1].productCode
                            memberActionBuy.text =
                                "${mActivity.getString(R.string.dollar_sign)}${entity.data.productDescriptions[1].price} ${
                                    mActivity.getString(R.string.purchase_now)
                                }"

                            txtVipBuyActions.visibility =
                                if (entity.data.autoRenew == 2) View.GONE else {
                                    if (entity.data.memberCode == null) View.GONE else {
                                        if (alreadyBuyProductCode == productCode) View.VISIBLE else View.GONE
                                    }
                                }
                            linearVipBuyBottomContainers.visibility =
                                if (entity.data.autoRenew == 2) View.VISIBLE else {
                                    if (entity.data.memberCode == null) View.VISIBLE else {
                                        if (alreadyBuyProductCode == productCode) View.GONE else View.VISIBLE
                                    }
                                }


                        }

                        conVipBuyWeeksContainers.setOnClickListener {
                            conVipBuyQuarterContainers.setBackgroundResource(R.drawable.shape_ccb0ff_radius_10)
                            entity.data.productDescriptions[2].check = false

                            conVipBuyMonthlyContainers.setBackgroundResource(R.drawable.shape_ccb0ff_radius_10)
                            entity.data.productDescriptions[1].check = false


                            conVipBuyWeeksContainers.setBackgroundResource(R.drawable.shape_ccb0ff_c02ed8_stroke_2_radius_10)
                            entity.data.productDescriptions[0].check = true

                            memberActionBuy.text =
                                "${mActivity.getString(R.string.dollar_sign)}${entity.data.productDescriptions[0].price} ${
                                    mActivity.getString(R.string.purchase_now)
                                }"
                            productCode = entity.data.productDescriptions[0].productCode
                            txtVipBuyActions.visibility =
                                if (entity.data.autoRenew == 2) View.GONE else {
                                    if (entity.data.memberCode == null) View.GONE else {
                                        if (alreadyBuyProductCode == productCode) View.VISIBLE else View.GONE
                                    }
                                }
                            linearVipBuyBottomContainers.visibility =
                                if (entity.data.autoRenew == 2) View.VISIBLE else {
                                    if (entity.data.memberCode == null) View.VISIBLE else {
                                        if (alreadyBuyProductCode == productCode) View.GONE else View.VISIBLE
                                    }
                                }


                        }
                    }
                    rvVipBuyEquityLists.layoutManager = LinearLayoutManager(mActivity)
                    val subscriptions = entity.data.subscriptions
                    rvVipBuyEquityLists.adapter = MemberSubscriptionAdapter(subscriptions, mActivity)

                    txtVipBuyActions.setOnClickListener {
                        val dialog =
                            CommonPopup(mActivity).setTitle(mActivity.getString(R.string.unsubscribe))
                                .setContent(mActivity.getString(R.string.unsubscribe_tip))
                                .setConfirmText(mActivity.getString(R.string.unsubscribe))
                                .setCancelText(mActivity.getString(R.string.cancel))
                        dialog.setConfirmListener {
                            OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
                                override fun addBody(requestBody: OkHttpBodyEntity) {
                                    requestBody.setPost(Constant.user_off_auto_renew_url)
                                }
                            }, object : SDOkHttpResoutCallBack<MemberSubscribeEntity>() {
                                override fun onSuccess(entity: MemberSubscribeEntity) {
                                    FirebaseEventUtils.logEvent(FirebaseEventTag.Me_Member_Premium_Unsub.name)
                                    getData()
                                }
                            })
                            dialog.dismiss()
                        }
                        dialog.showPopupWindow()
                    }
                }

            })
        }

    }


}
